创建一个异步Server
对象。
$serv = new Server(string $host, int $port = 0, int $mode = SWOOLE_PROCESS,
int $sock_type = SWOOLE_SOCK_TCP);
$host
参数用来指定监听的ip地址,如127.0.0.1
,或者外网地址,或者0.0.0.0
监听全部地址- IPv4使用
127.0.0.1
表示监听本机,0.0.0.0
表示监听所有地址 - IPv6使用
::1
表示监听本机,::
(相当于0:0:0:0:0:0:0:0
) 表示监听所有地址
- IPv4使用
$port
监听的端口,如9501
- 如果
$sock_type
为UnixSocket Stream/Dgram
,此参数将被忽略 - 监听小于
1024
端口需要root
权限 - 如果此端口被占用
server->start
时会失败
- 如果
$mode
运行的模式SWOOLE_PROCESS
多进程模式(默认)SWOOLE_BASE
基本模式
$sock_type
指定Socket
的类型,支持TCP
、UDP
、TCP6
、UDP6
、UnixSocket Stream/Dgram
6种- 使用
$sock_type | SWOOLE_SSL
可以启用SSL
隧道加密。启用SSL
后必须配置ssl_key_file和ssl_cert_file 1.7.11
版本增加了对Unix Socket
的支持,详细请参见 /wiki/page/16.html- 构造函数中的参数与
swoole_server::addlistener
中是完全相同的 - 高负载的服务器,请务必调整Linux内核参数
- 2种Server运行模式介绍
监听端口失败会抛出异常,可以使用try/catch
捕获异常
- 底层有保护机制,一个
PHP
程序内只能创建启动一个Server
实例 - 如果要实现多个
Server
实例的管理,父进程必须使用exec
,不得使用fork
1.9.6
增加了随机监听可用端口的支持,$port
参数可以设置为0,操作系统会随机分配一个可用的端口,进行监听。可以通过读取$server->port
得到分配到的端口号。
$http = new Swoole\Http\Server("0.0.0.0");
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
1.9.7
增加了对systemd socket
的支持。监听端口由systemd
配置指定。
[Unit]
Description=Swoole Socket
[Socket]
ListenStream=9501
Accept=false
[Install]
WantedBy = sockets.target
[Service]
Type=forking
PIDFile=/var/run/swoole.pid
ExecStart=/usr/bin/php /var/www/swoole/server.php
ExecStop=/bin/kill $MAINPID
ExecReload=/bin/kill -USR1 $MAINPID
[Install]
WantedBy = multi-user.target
$http = new Swoole\Http\Server("systemd");
$http->set([
'daemonize' => true,
'pid_file' => '/var/run/swoole.pid',
]);
$http->on('request', function ($request, $response) {
$response->header("Content-Type", "text/html; charset=utf-8");
$response->end("<h1>Hello Swoole. #".rand(1000, 9999)."</h1>");
});
$http->start();
sudo systemctl enable swoole.socket
sudo systemctl start swoole.socket
sudo systemctl start swoole.service